package se.hrbustrc.hlgshopping.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 设置缓存
     */
    public void set(String key, Object value, Long expireTime) {
        redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.MILLISECONDS);
    }

    /**
     * 获取缓存
     */
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除缓存
     */
    public Boolean delete(String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 判断缓存是否存在
     */
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 设置用户token到Redis
     */
    public void setUserToken(String username, String token) {
        redisTemplate.opsForValue().set("user_token:" + username, token, 24, TimeUnit.HOURS);
    }

    /**
     * 获取用户token
     */
    public String getUserToken(String username) {
        Object token = redisTemplate.opsForValue().get("user_token:" + username);
        return token == null ? null : (String) token;
    }

    /**
     * 删除用户token
     */
    public void deleteUserToken(String username) {
        redisTemplate.delete("user_token:" + username);
    }
}
